/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int postIndex = 0;
    public TreeNode createTreeByPandI(int[] inorder,int inbegin,int inend,int[] postorder){
        if(inbegin > inend) return null;
        TreeNode root = new TreeNode(postorder[postIndex]);
        int rootIndex = findIndex(inorder,inbegin,inend,root.val);
        if(rootIndex == -1) return null;
        postIndex--;
        root.right = createTreeByPandI(inorder,rootIndex+1,inend,postorder);
        root.left = createTreeByPandI(inorder,inbegin,rootIndex-1,postorder);
        return root;
    }
    
    public int findIndex(int[] inorder,int inbegin,int inend,int key){
        for(int i = inend ; i >= inbegin ; i--){
            if(inorder[i] == key){
                return i;
            }
        }
        return -1;
    }

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex = postorder.length-1;
        if(inorder == null || postorder == null) return null;
        return createTreeByPandI(inorder,0,postorder.length-1,postorder);
    }
}